<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\mill\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\user\model\UserGroup as UserGroupModel;
use app\mill\model\Archives as ArchivesModel;
use app\mill\model\Give as GiveModel;
use app\mill\model\Order as OrderModel;
use app\user\model\User as UserModel;
use app\mill\model\Client as ClientModel;
use think\Db;

/**
 * 生产管理控制器
 * @package app\admin\controller
 */
class Give extends Admin
{
    /**
     * 工程列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $map0 = $map01 = $this->getMap();
        //$map[] = ['status','in','0,-1'];
        $map[] = $map0[] = $map01[] = ['archives_status','in','2'];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->field('*,client_id as client_id2')
            ->where($map)
            ->order('status asc,id desc')
            ->paginate()
            ->each(function ($v){

                $v['number_sum'] = Db::name('mill_order_archives')->where(['order_id'=>$v['id']])->sum('number');

                return $v;
            })
        ;
        //待审核
        $map0[] = ['status','eq','0'];
        $total0 = Db::name('mill_order')->where($map0)->count();
        //未通过
        $map01[] = ['status','eq','-1'];
        $total01 = Db::name('mill_order')->where($map01)->count();

        //JS
        $js = '<script type="text/javascript">
                $(function(){
                    $(".archivesEdit_btn").css("display","none");
                    $(".archives_drawing").text("面积表详情");
                    $(".archives_drawing").click(function(){
                        window.location.href = $(this).parents("tr").find("[data-files='."'".'archivesEdit'."'".']").attr("href");
                    })
                });
            </script>';

        $company = ClientModel::getList('company');
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('部门审核（待审核'.$total0.'/未通过'.$total01.'）') // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox(true)
            ->setSearchArea([
                ['text:2', 'archives_sn', '档案号', 'like'],
                ['select:2', 'client_id', '客户公司','','',$company],
                ['text:2', 'engineering', '工程名称', 'like'],
                //['daterange:2', 'back_status_time', '合同签订日期'],
                ['select:2', 'status', '审核状态','','',[0=>'待审核',1=>'已审核',-1=>'未通过']],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                //['back_status_time', '合同签订日期','date'],
                ['archives_sn', '档案号'],
                ['client_id2','客户公司','','',$company],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                //['money_str', '订金'],
                ['back', '跟单人'],
                ['archives_drawing','面积表','files.edit'],
                ['number_sum','产品总量'],
                /*['give_status','工程状态','callback',function($value, $data){
                    $status = GiveModel::$give_status[$value];
                    if($value == 0 && $data['status']<=0){
                        $status = OrderModel::status_tag($data['status'],OrderModel::$status[$data['status']]);
                        if($data['status'] == -1){
                            $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                        }
                    }
                    return $status;
                },'__data__'],*/
                ['status','工程状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,OrderModel::$status[$value]);
                    if($value == -1){
                        $status .= '<br/><a href="javascript:void(0);" onclick="layer.alert(\''.$data['status_note'].'\', {title: \'审核不通过原因\'});">[查看原因]</a>';
                    }
                    return $status;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->setExtraJs($js)
            //->addRightButton('enable',['title' => '审核通过'])
            ->addRightButton('enable',['title' => '审核通过','href' => url('urgent',['id' => '__id__']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核通过', 'font-size:24px;text-align: center;']])
            ->addRightButton('notDisable',['title' => '审核不通过','href' => url('mill/order/notDisable',['id' => '__id__','field'=>'status']),'icon'=>''],['area' => ['780px', '50%'], 'title' => ['审核不通过原因', 'font-size:24px;text-align: center;']])
            ->addRightButton('archives',['title' => '查看所有批次','href' => url('archives',['order_pid' => '__order_pid__']),'class'=>'btn btn-default','icon'=>''])
            ->addRightButton('archivesShow',['title' => '面积表详情','href' => url('archivesShow',['id' => '__id__']),'data-files'=>'archivesEdit','class'=>'archivesEdit_btn','icon'=>''])
            ->replaceRightButton(['status' => ['in', '1']], '', 'enable,notDisable')
            ->replaceRightButton(['status' => ['<>', '1']], '', 'archives')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'note'  => 100,
                'mobile'  => 100,
                'engineering'  => 150,
                'money_str'  => 60,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 启用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function enable($record = [])
    {
        return $this->setStatus('enable');
    }
    /**
     * 禁用
     * @param array $record 行为日志
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function disable($record = [])
    {
        return $this->setStatus('disable');
    }
    /**
     * 设置客户状态：删除、禁用、启用
     * @param string $type 类型：delete/enable/disable
     * @param array $record
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function setStatus($type = '', $record = [])
    {
        $ids = $this->request->isPost() ? input('post.ids/a') : input('param.ids');
        $ids = (array)$ids;

        foreach ($ids as $id) {

            switch ($type) {
                case 'enable':
                    if (false === OrderModel::where('id', $id)->setField('status', 1)) {
                        $this->error('审核失败，工程ID：'.$id);
                    }
                    break;
                case 'disable':
                    if (false === OrderModel::where('id', $id)->setField('status', -1)) {
                        $this->error('审核失败，工程ID：'.$id);
                    }
                    break;
                case 'delete':

                    if (false === OrderModel::where('id', 'in', $id)->delete()) {
                        $this->error('删除失败，工程ID：'.$id);
                    }
                    break;
                default:
                    $this->error('非法操作');
            }

            OrderModel::where('id', $id)->setField('status_verify_uid', UID);
            OrderModel::where('id', $id)->setField('status_time', time());

            action_log('role_'.$type, 'mill', $id, UID);
        }

        $this->success('操作成功');
    }
    /**
     * 加急
     */
    public function urgent()
    {
        $id = input('id');
        $info = Db::name('mill_order')->where(['id'=>$id])->find();

        if ($this->request->isPost()) {
            $data = input();
            $update = [
                'urgent_status'         =>  $data['urgent_status'],
                //'is_process'            =>  $data['is_process'],
                'status'                =>  1,
                'status_verify_uid'     =>  UID,
                'status_time'           =>  time(),
            ];
            if(!empty($data['urgent_status_time']))$update['urgent_status_time'] = strtotime($data['urgent_status_time']);

            Db::name('mill_order')->where(['id'=>$id])->update($update);

            //查询该工程是否有财务板块初始数据，没有则新增
            $finance = Db::name('mill_finance')->where(['order_pid'=>$info['order_pid'],'pid'=>0])->find();
            if(empty($finance)){
                $info['company'] = Db::name('mill_client')->where(['id'=>$info['client_id']])->value('company');
                $info['row_area'] = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where(['g.order_pid'=>$info['order_pid'],'g.status'=>4])
                    ->sum('a.one_area');
                $add = [
                    'order_pid'         =>  $info['order_pid'],
                    'order_sn'          =>  $info['order_sn'],
                    'engineering'       =>  $info['engineering'],
                    'company'           =>  $info['company'],
                    'address_area'      =>  $info['row_area'],
                    'create_time'       =>  time(),
                    'update_time'       =>  time(),
                ];
                Db::name('mill_finance')->insert($add);
            }

            action_log('role_enable', 'mill', $id, UID);

            $this->success('操作成功', null, '_parent_reload');
        }

        $info = Db::name('mill_order')->where(['id'=>$id])->find();
        $info['title'] = "{$info['order_sn']} 第{$info['batch']}批 {$info['engineering']}";

        return ZBuilder::make('form')
            ->setPageTitle('审核通过') // 页面标题
            ->addFormItem('hidden', 'id')
            ->addStatic('title', '工程')
            ->addFormItems([ // 批量添加表单项
                //['radio:||||must', 'is_process', '是否复合','',['0'=>'不复合','1'=>'复合'],'0'],
                ['radio:||||must', 'urgent_status', '生产进度','',['0'=>'正常','1'=>'加急','2'=>'特急'],'0'],
                ['date:||||must', 'urgent_status_time', '出货日期'],

            ])
            ->setFormData($info)
            ->layout(['urgent_status'=>12,'urgent_status_time'=>12,'title'=>12,'is_process'=>12])
            ->fetch();
    }
    /**
     * 面积表详情
     * @param null $id 工程id
     * @return mixed
     */
    public function archivesShow($id=null)
    {

        $action = new Order();
        return $action->archivesEdit($id,false);
    }
    /**
     * 所有批次
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archives($role='')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $order_pid = input('order_pid');
        $map[] = ['order_pid','=',$order_pid];
        $map[] = ['archives_status','=',2];
        // 数据列表
        $data_list = Db::name('mill_order')
            ->where($map)
            ->order('id asc')
            ->paginate()
            ->each(function ($v){
                $archvices = ArchivesModel::getOneStat($v['id'],'order_id');
                $v = array_merge($v,$archvices);

                /*$v['row_area'] = $v['number']*$v['one_area'];

                $where = ['archives_id'=>$v['id'],'status'=>$v['a_status']];
                //已完成数
                $v['status_ok_sum'] = Db::name('mill_order_archives_give')->where($where)->count();
                //未完成数
                $v['status_no_sum'] = $v['number']-$v['status_ok_sum'];
                //已完成面积
                $v['area_ok_sum'] = $v['one_area']*$v['status_ok_sum'];
                //未完成面积
                $v['area_no_sum'] = $v['row_area']-$v['area_ok_sum'];*/

                return $v;
            })
        ;
        //批次统计
        $order_ids = Db::name('mill_order')->where($map)->column('id','id');
        $archvices = ArchivesModel::getOneStat(implode(',',$order_ids),'order_id','in');

        //$archvices_str = "产品总量：{$archvices['number_sum']}&nbsp;&nbsp;&nbsp;&nbsp;总面积：{$archvices['area_sum']}&nbsp;&nbsp;&nbsp;&nbsp;已完成面积：{$archvices['area_ok_sum']}&nbsp;&nbsp;&nbsp;&nbsp;未完成面积：{$archvices['area_on_sum']}&nbsp;&nbsp;&nbsp;&nbsp;开料：{$archvices['status1']}&nbsp;&nbsp;&nbsp;&nbsp;钣金：{$archvices['status2']}&nbsp;&nbsp;&nbsp;&nbsp;喷涂：{$archvices['status3']}&nbsp;&nbsp;&nbsp;&nbsp;复合：{$archvices['status4']}&nbsp;&nbsp;&nbsp;&nbsp;发货：{$archvices['status5']}";
        $archvices_str = "产品总量：{$archvices['number_sum']}&nbsp;&nbsp;&nbsp;&nbsp;总面积：{$archvices['area_sum']}&nbsp;&nbsp;&nbsp;&nbsp;已完成面积：{$archvices['area_ok_sum']}&nbsp;&nbsp;&nbsp;&nbsp;未完成面积：{$archvices['area_on_sum']}&nbsp;&nbsp;&nbsp;&nbsp;开料：{$archvices['status1']}&nbsp;&nbsp;&nbsp;&nbsp;发货：{$archvices['status5']}";

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("{$data_list[0]['engineering']} 工程所有批次") // 页面标题
            ->setTableName('mill_order') // 设置表名
            ->hideCheckbox()
            ->setPageTips($archvices_str)
            ->addColumns([ // 批量添加列
                //['id', '序号'],
                ['archives_sn', '档案号'],
                ['batch', '产品批次'],
                ['number_sum', '产品总量'],
                ['area_sum', '总面积'],
                ['area_ok_sum', '已完成面积'],
                ['area_on_sum', '未完成面积'],
                ['status1', '开料'],
                //['status2', '钣金'],
                //['status3', '喷涂'],
                //['status4', '复合'],
                ['status5', '发货'],
                ['status_time', '审核日期','date'],
                ['archives_sign_time', '图纸确认日期','date'],
                //['is_process', '是否复合','switch'],
                //['archives_handle','经办人'],
                ['right_button', '操作', 'btn']
            ])
            ->addRightButton('archivesGive',['title' => '查看详情','href' => url('archivesGive'.$role,['id' => '__id__']),'class'=>'btn btn-default disable-dch','icon'=>''])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    public function archives2(){
        return $this->archives(3);
    }
    public function archives3(){
        return $this->archives(3);
    }
    public function archivesGive2(){
        return $this->archivesGive();
    }
    public function archivesGive3(){
        return $this->archivesGive();
    }
    public function archivesGive()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $status = '';
        $quality_repair = '';
        $sort_between = [];
        $map = $this->getMap();
        $map2 = '';
        if(!empty($map)){
            foreach ($map as $k=>$v){
                if(in_array('a_sort',$v)){
                    $a_sort = explode('-',$v[2]);
                    $sort = !empty($a_sort[0])?$a_sort[0]:'';
                    $counter = !empty($a_sort[1])?$a_sort[1]:'';
                    unset($map[$k]);
                }
                elseif(in_array('g.status',$v)){
                    $status = $v[2];
                }
                elseif(in_array('a_sort1',$v)){
                    $sort_between[0] = $v[2];
                    unset($map[$k]);
                }
                elseif(in_array('a_sort2',$v)){
                    $sort_between[1] = $v[2];
                    unset($map[$k]);
                }
                elseif(in_array('g.quality_repair',$v)){
                    $quality_repair = $v[2];
                }
            }
        }
        // 获取查询条件
        $id = input('id');
        $map[] = ['g.order_id','=',$id];
        if(is_numeric($status)){
            $map[] = ['g.quality_status','>=',0];
        }
        $archives_id = input('archives_id');
        if($archives_id)$map[] = ['g.archives_id','=',$archives_id];
        if(!empty($sort))$map[] = ['a.sort','=',$sort];
        if(!empty($counter))$map[] = ['g.counter','=',$counter];

        $str_int = 999999;
        if(count($sort_between) == 2){
            $sort_between2 = [];
            if(strpos($sort_between[0],'-') && strpos($sort_between[1],'-')){
                $sort_between2[0] = explode('-',$sort_between[0])[1];
                $sort_between2[1] = explode('-',$sort_between[1])[1];

                $sort_between[0] = explode('-',$sort_between[0])[0];
                $sort_between[1] = explode('-',$sort_between[1])[0];
            }
            if(strpos($sort_between[0],'#') || strpos($sort_between[1],'#')){
                $sort_between[0] = str_replace('#',$str_int,$sort_between[0]);
                $sort_between[1] = str_replace('#',$str_int,$sort_between[1]);
            }
            $map2 .= " CONVERT (REPLACE(a.sort,'#','{$str_int}'),signed) BETWEEN {$sort_between[0]} AND {$sort_between[1]} ";
            if(!empty($sort_between2))$map2 .= " and g.counter BETWEEN {$sort_between2[0]} AND {$sort_between2[1]} ";
        }
        sort($map);

        //检查工程是否已审核
        $is_order = Db::name('mill_order')->where(['id'=>$id,'status'=>1])->count();
        if(empty($is_order))$this->error('该工程未审核，请前往部门审核');

        //更新产品明细
        ArchivesModel::checkGive($id,$archives_id);

        $archvices = ArchivesModel::getOneStat($id);

        //$archvices_str = "产品总量：{$archvices['number_sum']}&nbsp;&nbsp;&nbsp;&nbsp;总面积：{$archvices['area_sum']}&nbsp;&nbsp;&nbsp;&nbsp;已完成面积：{$archvices['area_ok_sum']}&nbsp;&nbsp;&nbsp;&nbsp;未完成面积：{$archvices['area_on_sum']}&nbsp;&nbsp;&nbsp;&nbsp;开料：{$archvices['status1']}&nbsp;&nbsp;&nbsp;&nbsp;钣金：{$archvices['status2']}&nbsp;&nbsp;&nbsp;&nbsp;喷涂：{$archvices['status3']}&nbsp;&nbsp;&nbsp;&nbsp;复合：{$archvices['status4']}&nbsp;&nbsp;&nbsp;&nbsp;发货：{$archvices['status5']}";
        $archvices_str = "产品总量：{$archvices['number_sum']}&nbsp;&nbsp;&nbsp;&nbsp;总面积：{$archvices['area_sum']}&nbsp;&nbsp;&nbsp;&nbsp;已完成面积：{$archvices['area_ok_sum']}&nbsp;&nbsp;&nbsp;&nbsp;未完成面积：{$archvices['area_on_sum']}&nbsp;&nbsp;&nbsp;&nbsp;开料：{$archvices['status1']}&nbsp;&nbsp;&nbsp;&nbsp;发货：{$archvices['status5']}";

        // 数据列表
        $_listRows = input('list_rows',GiveModel::$_listRows);
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('g.*,g.give_sn as give_sn_img,a.model,a.thickness,a.one_area,a.color,a.sort as a_sort,a.page,a.model_sn,a.cutting,a.size,a.long,a.high,a.plank')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($map)
            ->where($map2)
            ->orderRaw("CONVERT (REPLACE(a.sort,'#','{$str_int}'),signed) asc,g.id asc")
            ->select();
        //->paginate($_listRows);

        //工程信息
        $order = Db::name('mill_order')->where(['id'=>$id])->find();

        //JS
        $js = '
        <script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script>
        <script type="text/javascript">
            $(function(){
                $(".barcode").each(function(i){
                    var val = $(this).data("val");
                    $(this).JsBarcode(val,{displayValue:false});
                });
            })
        </script>
        ';
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle("{$order['engineering']} {$order['archives_sn']} 产品明细") // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            //->hideCheckbox()
            ->setPageTips($archvices_str)
            ->setSearchArea([
                ['select:2', 'g.quality_repair', '打印状态', 'eq','',GiveModel::$quality_repair],
                ['select:2', 'g.status', '产品状态', 'eq','',GiveModel::$give_status_search],
                ['text:1', 'a_sort', '序号查询'],
                ['text:1', 'a_sort1', '序号范围查询1'],
                ['text:1', 'a_sort2', '序号范围查询2'],
            ])
            ->addColumns([ // 批量添加列
                ['sort', '序号'],
                ['page', '图号'],
                ['model_sn', '编号'],
                ['thickness', '板厚MM'],
                ['long', '长(L)'],
                ['high', '宽(W)'],
                ['one_area', '单件面积M²'],
                ['color', '颜色'],
                ['model', '板型'],
                //['plank', '板材'],
                ['a_sort','序号','callback',function($value, $data){
                    $value = "{$value}-{$data['counter']}";
                    return $value;
                },'__data__'],
                ['give_sn','产品条形码编号','callback',function($value, $data){
                    if($data['quality_old_id']>0)$value .= '<a>(补)</a>';
                    return $value;
                },'__data__'],
                ['status','产品状态','callback',function($value, $data){
                    $str = '';

                    if($data['address_status']<0)$str = '<span class="label label-warning">已锁定</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
                    //质检
                    if($data['quality_status']<0)$uid = $data['quality_uid'];
                    //生产
                    else $uid = GiveModel::giveStatusOrUid($data['status_flow'],'',$value);
                    //部门信息
                    if($uid){
                        $user = Db::name('admin_user')
                            ->alias('u')
                            ->field('u.nickname,g.name as group_name')
                            ->leftJoin('admin_user_group g','g.id=u.group')
                            ->where(['u.id'=>$uid])
                            ->find();
                        if($user)$str .= "{$user['group_name']}[{$user['nickname']}]：";
                    }

                    $str .= '<span class="label label-primary">'.GiveModel::$give_status[abs($value)];
                    if($data['quality_status']<0)$str .= GiveModel::$quality_status[$data['quality_status']];
                    $str .= '</span>';

                    return $str;
                },'__data__'],
                ['quality_repair','打印状态','callback',function($value, $data){
                    $status = OrderModel::status_tag($value,GiveModel::$quality_repair[$value]);
                    return $status;
                },'__data__'],
                ['give_sn_img','产品条形码','callback',function($value, $data){
                    //$value = '<div class="js-gallery"> <img class="image" data-original="'.plugin_url('Barcode/Barcode/generate', ['text' => $value]).'" src="'.plugin_url('Barcode/Barcode/generate', ['text' => $value]).'"></div>';
                    $value = '<div class="js-gallery"> <img class="image barcode" data-val="'.$value.'" data-original="" src=""></div>';
                    return $value;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('able',['title' => '更新状态','href' => url('able',['order_id' => $id]),'icon'=>'','class'=>'btn btn-primary disable-dch'],['area' => ['780px', '90%'], 'title' => ['批量更新产品状态', 'font-size:24px;text-align: center;']])
            ->addTopButton('addressDisable',['title' => '批量锁定','href' => url('addressDisable',['address_status' => -1]),'icon'=>'','class'=>'btn btn-primary ajax-post confirm'])
            ->addTopButton('addressDisable',['title' => '批量解锁','href' => url('addressDisable',['address_status' => 0]),'icon'=>'','class'=>'btn btn-primary ajax-post confirm'])
            ->addTopButton('archivesPrint',['title' => '批量打印(不带LOGO)','href' => url('archivesPrint',['order_id' => $id,'archives_id'=>$archives_id,'status'=>$status,'quality_repair'=>$quality_repair,'page'=>input('page',1),'list_rows'=>$_listRows]),'icon'=>'','class'=>'btn btn-primary dch-js-get'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addTopButton('archivesPrint',['title' => '批量打印(带LOGO)','href' => url('archivesPrint',['order_id' => $id,'archives_id'=>$archives_id,'status'=>$status,'quality_repair'=>$quality_repair,'watermark'=>1,'page'=>input('page',1),'list_rows'=>$_listRows]),'icon'=>'','class'=>'btn btn-primary dch-js-get'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addRightButton('archivesPrint',['title' => '打印(不带LOGO)','href' => url('archivesPrint',['id' => '__id__','page'=>1]),'class'=>'btn btn-default disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addRightButton('archivesPrint',['title' => '打印(带LOGO)','href' => url('archivesPrint',['id' => '__id__','watermark'=>1,'page'=>1]),'class'=>'btn btn-default disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->setColumnWidth([
                'sort'    =>  50,
                'page'    =>  65,
                'cutting'    =>  50,
                'size'    =>  50,
                'one_area'    =>  80,
                'long'    =>  52,
                'high'    =>  52,
                'color'    =>  120,
                'thickness'    =>  60,
                'a_sort'    =>  60,
                'give_sn'    =>  130,
                'status'    =>  150
            ])// 设置列宽
            ->setExtraJs($js)
            ->setRowList($data_list) // 设置表格数据
            //->noPages()
            ->fetch(); // 渲染模板
    }
    //发货锁定
    public function addressDisable()
    {
        $ids = input('ids');
        //-1:禁止发货 0:待发货
        $address_status = input('address_status');
        if(empty($ids))$this->error("请选择产品");
        foreach ($ids as $id){
            $give = Db::name('mill_order_archives_give')
                ->alias('g')
                ->field('g.*,g.give_sn as give_sn_img,a.model,a.thickness,a.one_area,a.color,a.sort as a_sort,a.page,a.model_sn,a.cutting,a.size,a.long,a.high,a.plank')
                ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                ->where(['g.id'=>$id])->find();
            if(empty($give))$this->error('该产品不存在');
            if($give['address_status'] > 0)$this->error("序号[{$give['a_sort']}-{$give['counter']}]已发货");
        }
        Db::name('mill_order_archives_give')->where([['id','in',implode(',',$ids)]])->update(['address_status'=>$address_status]);

        //$this->success('操作成功','','_parent_reload');
        $this->success('操作成功');
    }
    /**
     * 需打印的补件产品信息
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesRepairGive($quality_old_id = null,$quality_repair = '1')
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = [
            ['g.quality_repair','in',$quality_repair],
        ];
        //根据原件ID查补件
        if($quality_old_id){
            $quality_old_str = explode('_',$quality_old_id);
            if(empty($quality_old_str[1]))$quality_old_str[1] = 'eq';
            $map[] = ['g.quality_old_id',$quality_old_str[1],$quality_old_str[0]];
        }

        // 数据列表
        $_listRows = input('list_rows',GiveModel::$_listRows);
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field('g.*,a.model,a.thickness,a.one_area,a.color,o.engineering')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($map)
            ->order('g.id asc')
            ->paginate($_listRows);

        $title = '补件中';
        if($quality_old_id)$title = '补件产品明细';
        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            ->hideCheckbox()
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案编号'],
                ['engineering', '工程名称'],
                ['give_sn', '产品条形码编号'],
                ['model', '铝板板型'],
                ['thickness', '板厚MM'],
                ['one_area', '面积M²'],
                ['number', '数量'],
                ['color', '颜色'],
                //['status', '产品状态',GiveModel::$give_status],
                ['status','产品状态','callback',function($value, $data){
                    $value = GiveModel::$give_status[abs($value)];
                    if($data['quality_status']<0)$value .= GiveModel::$quality_status[$data['quality_status']];
                    return $value;
                },'__data__'],
                ['give_sn','产品条形码','callback',function($value, $data){
                    $value = '<div class="js-gallery"> <img class="image" data-original="'.plugin_url('Barcode/Barcode/generate', ['text' => $value]).'" src="'.plugin_url('Barcode/Barcode/generate', ['text' => $value]).'"></div>';
                    return $value;
                },'__data__'],
                ['right_button', '操作', 'btn']
            ])
            ->addTopButton('archivesPrint',['title' => '批量打印','href' => url('archivesPrint',['quality_repair' => 1,'quality_old_id'=>$quality_old_id,'page'=>input('page',1),'list_rows'=>$_listRows]),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addTopButton('archivesPrint',['title' => '批量打印(带LOGO)','href' => url('archivesPrint',['quality_repair' => 1,'quality_old_id'=>$quality_old_id,'watermark'=>1,'page'=>input('page',1),'list_rows'=>$_listRows]),'icon'=>'','class'=>'btn btn-primary'],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addRightButton('archivesPrint',['title' => '打印','href' => url('archivesPrint',['id' => '__id__','page'=>1]),'class'=>'btn btn-default disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->addRightButton('archivesPrint',['title' => '打印(带LOGO)','href' => url('archivesPrint',['id' => '__id__','watermark'=>1,'page'=>1]),'class'=>'btn btn-default disable-dch','icon'=>''],['area' => ['780px', '90%'], 'title' => ['正在打印中...', 'font-size:24px;text-align: center;']])
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'thickness'  => 50,
                'number'  => 30,
                'one_area'  => 50,
                'status'  => 50,
                'engineering'  => 150,
            ])
            //->noPages()
            ->fetch(); // 渲染模板
    }
    /**
     * 补件产品信息
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesRepairGiveList()
    {

        $quality_old_id = '0_gt';
        $quality_repair = '2';
        return $this->archivesRepairGive($quality_old_id,$quality_repair);
    }
    /**
     * 打印条形码
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function archivesPrint(){

        //打印单个条形码
        $id = input('id');
        //批量打印条形码
        $ids = input('ids');
        $status = input('status');
        $order_id = input('order_id');
        $archives_id = input('archives_id');
        //批量打印补件条形码
        $quality_repair = input('quality_repair');
        //根据原件ID查补件
        $quality_old_id = input('quality_old_id');
        //是否打印水印
        $watermark = input('watermark')?"<img style='width:45px;' src='".config('template.tpl_replace_string')['__ADMIN_IMG__']."/avatar.jpg'>":'';
        //$watermark = '';
        //是否更新打印状态
        $is_quality_repair = true;
        if($quality_repair == 1 || $quality_old_id)$is_quality_repair = true;

        $where = [['g.id','=',$id]];
        if(!empty($ids))$where = [['g.id','in',$ids]];
        elseif($order_id)$where = [['g.order_id','=',$order_id]];
        elseif($quality_old_id){
            $quality_old_str = explode('_',$quality_old_id);
            if(empty($quality_old_str[1]))$quality_old_str[1] = 'eq';
            $where = [['g.quality_old_id',$quality_old_str[1],$quality_old_str[0]]];
        }
        //elseif ($quality_repair)$where = [['g.quality_repair','=',$quality_repair]];

        if($archives_id)$where = [['g.archives_id','=',$archives_id]];
        if(is_numeric($status)){
            $where[] = ['g.status','=',$status];
            $where[] = ['g.quality_status','>=',0];
        }
        if(is_numeric($quality_repair)){
            $where[] = ['g.quality_repair','=',$quality_repair];
        }

        $give_id = '';
        $list_rows = input('list_rows',GiveModel::$_listRows);
        $page = input('page',1);
        if(!empty($id) || !empty($ids))$page = 1;
        $_listRows['list_rows'] = $list_rows;
        $_listRows['page'] = $page;
        $list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->field('a.*,o.batch,g.give_sn,g.counter,g.quality_old_id,g.id as give_id,g.sort as give_sort')
            ->where($where)
            //->orderRaw('convert(a.sort,signed),g.sort asc')
            ->order('g.id asc')
            ->select();
        //->paginate($_listRows);

        $html = '<html><head></head><body style="margin: 0;margin-left: 11px;">';

        if(!empty($list[0])){
            $order = Db::name('mill_order')->where(['id'=>$list[0]['order_id']])->find();
            //项目名称只保留前8位
            $order['engineering'] = mb_substr($order['engineering'],0,8);
            if(!empty($order['engineering_full']))$order['engineering'] = $order['engineering_full'];
            $i = count($list);
            foreach ($list as $k=>$v){

                $give_id .= ",{$v['give_id']}";

                $barcode = '<img style="width: 40mm" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/onload.gif" class="barcode" data-val="'.$v['give_sn'].'">';
                $barcode2 = '<img style="width: 38mm;margin-top: -5px;" src="'.config('template.tpl_replace_string')['__ADMIN_IMG__'].'/onload.gif" class="barcode" data-val="'.$v['give_sn'].'">';
                //是否补件
                if($v['quality_old_id']>0)$v['give_sn'] .= '(补件)';
//批<br>次 $v['batch']
                $margin = 'margin-bottom: 30px;';
                $width = '76mm';
                $height = '57mm';
                if($i == $k+1)$margin = '';
                //颜色字号大小
                $color_size = 18;
                if(mb_strlen($v['color']) > 14)$color_size = 14;
                $html .= '<table border="1" style="border-collapse: collapse;width: '.$width.';height: '.$height.';'.$margin.'">
<tbody>
<tr><td colspan="7" style="font-size: 16px;text-align: center;">'.$watermark.$barcode.'<br/>'.$v['give_sn'].'</td></tr>
<tr style="height: 25px"><th colspan="7" style="font-size: 16px;font-weight: 900;">'.$order['order_sn'].' ('.$order['engineering'].')'.$v['batch'].'</th></tr>
<tr style="height: 20px"><td style="width: 35px;">颜色</td><td colspan="6" style="font-size: '.$color_size.'px;font-weight: 900;">'.$v['color'].'</td></tr>
<tr style="height: 20px"><td rowspan="2" style="width: 35px">序号</td><td rowspan="2" colspan="1" style="font-size: 30px;width: 70px;font-weight: 900;">'.$v['sort'].'</td><td style="width: 35px;line-height: 15px;">图号</td><td colspan="3" style="font-size: 16px;line-height: 15px;">'.$v['page'].'</td></tr>
<tr style="height: 10px"><td style="width: 35px;line-height: 15px;">数量</td><td style="font-size: 24px;line-height: 15px;">'.$v['counter'].'/'.$v['number'].'</td></tr>
<tr style="height: 20px"><td style="width: 35px">编号</td><td colspan="6" style="font-size: 18px;font-weight: 900;">'.$v['model_sn'].'</td></tr>
</tbody>
</table>';
            }
        }
        if($html){
            $html .= '<script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/core/jquery.min.js?v=20180327"></script><script src="'.config('template.tpl_replace_string')['__ADMIN_JS__'].'/jsbarcode.all.min.js?v=20180327"></script><script type="text/javascript">
                $(function(){
                
                    $(".barcode").each(function(i){
                        var val = $(this).data("val");
                        $(this).JsBarcode(val,{height:61,margin:5,displayValue:false});
                    });
                    //调用打印功能
                    window.print();
                    
                });
            </script>';
        }

        $html .= '</body></html>';

        //默认已在打印中,更新打印状态
        $give_id = trim($give_id,',');
        if($is_quality_repair && $give_id){
            Db::name('mill_order_archives_give')
                ->where([['id','in',$give_id]])
                ->update(['quality_repair'=>2]);
        }
        //更新打印时间
        if(!empty($order) && empty($order['print_time']))Db::name('mill_order_archives_give')->where(['id'=>$order])->update(['print_time'=>time()]);

        echo $html;exit;

    }
    /**
     * 产品生产进度列表页
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function speed($archives_status=1,$read_type=0)
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $map3 = '';
        $archives_status2 = '';
        if(!empty($map)){
            foreach ($map as $m_v_i=>$m_v){
                if(in_array('a_sort',$m_v)){
                    $a_sort = explode('-',$m_v[2]);
                    $sort = !empty($a_sort[0])?$a_sort[0]:'';
                    $counter = !empty($a_sort[1])?$a_sort[1]:'';
                    unset($map[$m_v_i]);
                }
                elseif($m_v[0] == 'g.status'){
                    $archives_status = $m_v[2];
                    if(count(explode(',',$archives_status)) > 1){
                        $archives_status = explode(',',$archives_status)[0];
                        $archives_status2 = $archives_status;
                    }
                    unset($map[$m_v_i]);
                }
                elseif($m_v[0] == 'status_flow'){
                    $m_v[2] = trim($m_v[2],'%');
                    $m_v[2] = "%\\_{$archives_status}|".trim($m_v[2],'%')."\\_%";
                    $map[$m_v_i] = $m_v;
                }
                elseif ($m_v[0] == 'times'){
                    $m_v[2][0] = strtotime($m_v[2][0]);
                    $m_v[2][1] = strtotime($m_v[2][1]);
                    if($archives_status > 0){
                        if($read_type>0)$map3 .= "((g.status{$archives_status}_time between {$m_v[2][0]} and {$m_v[2][1]}))";
                        else $map3 .= "((g.quality_time between {$m_v[2][0]} and {$m_v[2][1]}) or (g.status{$archives_status}_time between {$m_v[2][0]} and {$m_v[2][1]}))";
                    }

                    unset($map[$m_v_i]);
                }

            }
        }
        $map = array_merge($map);
        $map[] = ['g.quality_status','>',-3];
        if(!empty($sort))$map[] = ['a.sort','=',$sort];
        if(!empty($counter))$map[] = ['g.counter','=',$counter];
        //生产状态：0待生产，1开料，2钣金，3喷涂喷涂，4发货
        if($archives_status == 0){
            $map2[] = ['g.status','=',0];
            $order = "id DESC";
        }
        else{
            if($read_type == 2)$map2[] = ['g.status','between',[0,($archives_status-1)]];
            elseif($read_type == 3)$map2[] = ['g.status','in',[$archives_status2]];
            else $map2[] = ['g.status_flow','like',"%\\_{$archives_status}|%"];

            $order = "(CASE WHEN g.quality_status<0 THEN g.quality_time ELSE g.status{$archives_status}_time END) DESC";
        }

        //获取所有负责人
        $user_list = UserModel::getList();
        unset($user_list[0]);
        unset($user_list[1]);

        // 数据列表
        $g_status_field = $archives_status;
        if($read_type == 2)$g_status_field = 'g.status';
        elseif($read_type == 3)$g_status_field = 'g.status';
        $_listRows = input('list_rows',GiveModel::$_listRows);
        $data_list = Db::name('mill_order_archives_give')
            ->alias('g')
            ->field("g.*,o.batch,o.order_sn_off as o_batch,a.model,a.model_sn,a.thickness,a.one_area,a.color,a.sort as a_sort,o.engineering,{$g_status_field} as g_status")
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->where($map)
            ->where($map2)
            ->where($map3)
            ->orderRaw($order)
            ->paginate($_listRows);

        //统计
        $data_stat = Db::name('mill_order')
            ->alias('o')
            ->field('sum(g.number) as number_sum,sum(a.one_area) as area_sum')
            ->leftJoin('mill_order_archives a','o.id=a.order_id')
            ->leftJoin('mill_order_archives_give g','a.id=g.archives_id')
            ->where($map)
            ->where($map2)
            ->where($map3)
            ->find();

        // 使用ZBuilder快速创建数据表格
        if($read_type == 2)$title = '未完成'.GiveModel::$give_status[$archives_status];
        elseif($read_type == 3)$title = '仓库';
        else $title = GiveModel::$give_status[$archives_status];

        $print_title = $title;
        $title .= '（总数量'.$data_stat['number_sum'].'/总面积'.$data_stat['area_sum'].'M²）';
        //if($read_type == 2)$title = '未完成'.$title;

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "'.$print_title.'",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        $url_parm = !empty($_SERVER['QUERY_STRING'])?"?{$_SERVER['QUERY_STRING']}":'';
        $print_url = url('mill/order/deliverGiveShowPrint',array('archives_status'=>$archives_status,'read_type'=>$read_type,'not_address'=>2)).$url_parm;

        //导出按钮
        $print_btn = ['title' => '导出列表','href'=>$print_url,'icon'=>'','class'=>'btn btn-success','target'=>'_blank'];
        //发货
        //if($archives_status == 5)$print_btn = ['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'];
        if($read_type == 0)$print_btn = ['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'];

        return ZBuilder::make('table')
            ->setPageTitle($title) // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            ->hideCheckbox()
            ->setSearchArea([
                //['select:1', 'g.status', '状态', '', '', GiveModel::$give_status_search],
                ['text:2', 'g.archives_sn', '档案编号', 'like'],
                ['text:2', 'engineering', '工程名称', 'like'],
                ['text:2', 'give_sn', '条码编号', 'like'],
                ['text:2', 'a_sort', '序号查询'],
                ['text:3', 'a.model_sn', '铝板编号', 'like'],
                ['text:2', 'a.color', '颜色', 'like'],
                ['select:2', 'status_flow', '扫码人', 'like', '', $user_list],
                ['daterange:2', 'times', '日期'],
            ])
            ->addColumns([ // 批量添加列
                ['archives_sn', '档案编号'],
                ['engineering', '工程名称'],
                ['batch', '批次'],
                ['model_sn', '铝板编号'],
                ['color', '颜色'],
                ['a_sort','序号','callback',function($value, $data){
                    $value = "{$value}-{$data['counter']}";
                    return $value;
                },'__data__'],
                ['give_sn', '产品条形码编号'],
                ['model', '铝板版型'],
                ['one_area', '面积M²'],
                ['number', '数量'],
                ['status_flow','扫码人','callback',function($value, $data){
                    $str = '';

                    //质检
                    if($data['quality_status']<0)$uid = $data['quality_uid'];
                    //生产
                    else $uid = GiveModel::giveStatusOrUid($value,'',$data['g_status']);
                    //部门信息
                    if($uid){
                        $user = Db::name('admin_user')
                            ->alias('u')
                            ->field('u.nickname,g.name as group_name')
                            ->leftJoin('admin_user_group g','g.id=u.group')
                            ->where(['u.id'=>$uid])
                            ->find();
                        if($user)$str .= "{$user['group_name']}[{$user['nickname']}]";
                    }

                    return $str;
                },'__data__'],
                ['quality_status','扫码时间','callback',function($value, $data){

                    $time = '';
                    //质检
                    if($value<0)$time = $data['quality_time'];
                    //生产
                    elseif(!empty($data["status".abs($data['g_status'])."_time"])) $time = $data["status".abs($data['g_status'])."_time"];
                    //格式
                    if($time)$time = date('Y.m.d H:i',$time);

                    return $time;

                },'__data__'],
                ['status','扫码状态','callback',function($value, $data){
                    $str = '';

                    $str .= '<span class="label label-primary">'.GiveModel::$give_status[$data['g_status']];
                    if($data['quality_status']<0)$str .= GiveModel::$quality_status[$data['quality_status']];
                    elseif ($data['quality_status'] == -3)$str = '<span class="label label-primary">'.GiveModel::$quality_status[$data['quality_status']];
                    $str .= '</span>';
                    return $str;
                },'__data__'],
            ])
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            //->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-success quality-print'])
            ->addTopButton('ablequality',$print_btn)
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'thickness'  => 50,
                'number'  => 30,
                'one_area'  => 50,
                'a_sort'  => 60,
                'give_sn'  => 110,
                'status'  => 60,
                'batch'  => 60,
                'engineering'  => 150,
            ])
            //->noPages()
            ->fetch(); // 渲染模板
    }
    /**
     * 开料列表页
     * @return mixed
     */
    public function cutting()
    {
        return $this->speed(1);
    }
    /**
     * 钣金列表页
     * @return mixed
     */
    public function plate()
    {
        return $this->speed(2);
    }
    /**
     * 喷涂喷涂列表页
     * @return mixed
     */
    public function spray()
    {
        return $this->speed(3);
    }
    /**
     * 复合列表页
     * @return mixed
     */
    public function process()
    {
        return $this->speed(4);
    }
    /**
     * 发货列表页
     * @return mixed
     */
    public function deliver()
    {
        return $this->speed(5);
    }
    /**
     * 质检管理列表页
     * @return mixed
     */
    public function quality($quality_status = null){
        cookie('__forward__', $_SERVER['REQUEST_URI']);

        // 获取查询条件
        $map = $this->getMap();
        $where = [
            //['g.quality_status','eq','-1']
        ];
        if($quality_status){
            $quality_status_str = explode('|',$quality_status);
            if(empty($quality_status_str[1]))$quality_status_str[1] = 'eq';
            $where = [
                ['g.quality_status',$quality_status_str[1],$quality_status_str[0]]
            ];
        }
        // 数据列表
        $data_list = Db::name('mill_order_archives_give_quality')
            ->alias('g')
            ->field('g.*,o.engineering,g.quality_flow_group,a.sort as a_sort,a.one_area,a.model_sn,a.thickness,a.color')
            ->leftJoin('mill_order o','o.id=g.order_id')
            ->leftJoin('mill_order_archives a','a.id=g.archives_id')
            ->where($where)
            ->where($map)
            ->order('g.quality_time desc')
            ->paginate();

        //部门列表
        $group_list = UserGroupModel::where('status=1')->column('id,name');

        //JS
        $js = '<script type="text/javascript">
                $(function() {
                    $(".quality-print").click(function(){
                        var table_head = $("#builder-table-head table thead").html();
                        var table_body = $("#builder-table-main tbody").html();
                        var table = \'<table id="table-print" stytle="display: none;">\' 
                        +\'<thead>\'+table_head+\'</thead>\'
                        +\'<tbody>\'+table_body+\'</tbody>\'
                        +\'</table>\';
                        $("#page-footer").append(table);
                        $("#table-print").table2excel({
                            // 不被导出的表格行的CSS class类
                            exclude: ".column-checkbox,.text-center,.column-right_button,.table-reigth-btn,.disable-dch,.hidden-xs",
                            // 导出的Excel文档的名称
                            name: "Excel Document Name",
                            // Excel文件的名称
                            filename: "全质量管理",
                            //文件后缀名
                            fileext: ".xls",
                            //是否排除导出图片
                            exclude_img: false,
                            //是否排除导出超链接
                            exclude_links: true,
                            //是否排除导出输入框中的内容
                            exclude_inputs: false
                        });
                    });
                })
            </script>';

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTitle('全质量管理（数量'.$data_list->total().'）') // 页面标题
            ->setTableName('mill_order_archives_give') // 设置表名
            ->setSearchArea([
                ['text:1', 'g.archives_sn', '档案编号', 'like'],
                ['text:2', 'g.give_sn', '条形码', 'like'],
                ['text:2', 'o.engineering', '工程名称', 'like'],
                ['select:2', 'g.quality_flow_group', '责任部门','','', $group_list],
                ['daterange:2', 'g.quality_time', '质检日期'],
            ])
            ->addColumns([ // 批量添加列
                ['id', '序号'],
                ['archives_sn', '档案编号'],
                ['give_sn', '产品条形码编号'],
                ['engineering', '工程名称'],
                ['quality_flow_group', '责任部门',$group_list],
                ['one_area', '面积'],
                ['a_sort', '序号'],
                ['model_sn', '铝板编号'],
                ['thickness', '板厚M²'],
                ['color','颜色'],
                ['quality_status','状态',GiveModel::$quality_status],
                ['quality_note','原因'],
                ['quality_time','质检时间','date'],
                //['right_button', '操作', 'btn']
            ])
            ->hideColumn('id', 'xs,sm,md,lg')
            ->js('jquery.table2excel', 'common')
            ->setExtraJs($js)
            ->addTopButton('ablequality',['title' => '批量质检','href' => url('ablequality'),'icon'=>'','class'=>'btn btn-primary dch-js-get'],['area' => ['780px', '90%'], 'title' => ['批量质检', 'font-size:24px;text-align: center;']])
            ->addTopButton('ablequality',['title' => '导出列表','icon'=>'','class'=>'btn btn-default quality-print'])
            //->addTopButton('ablequality',['title' => '批量修复','href' => url('ablequality',['status' => 1]),'icon'=>'','class'=>'btn btn-default ajax-post confirm'])
            //->addTopButton('ablequality',['title' => '批量报废','href' => url('ablequality',['status' => -2]),'icon'=>'','class'=>'btn btn-primary ajax-post confirm'])
            //->addRightButton('ablequality',['title' => '报废','href' => url('ablequality',['ids' => '__id__','status'=>-2]),'class'=>'btn btn-default ajax-get confirm','icon'=>''])
            //->addRightButton('ablequality',['title' => '修复','href' => url('ablequality',['ids' => '__id__','status'=>1]),'class'=>'btn btn-default ajax-get confirm','icon'=>''])
            //->replaceRightButton(['quality_status' => ['in', '-2']], '','ablequality')
            ->setRowList($data_list) // 设置表格数据
            ->setColumnWidth([
                'id'  => 60,
                'give_sn'  => 110,
                'quality_note'  => 150,
                'engineering'  => 150,
                'batch'  => 60,
            ])
            ->fetch(); // 渲染模板
    }
    /**
     * 质检管理报废列表页
     * @return mixed
     */
    public function qualityScrap(){

        $quality_status = '-2|eq';
        return $this->quality($quality_status);
    }
    /**
     * 质检管理 报废or修复
     * @return mixed
     */
    public function ablequality()
    {
        $user = session('user_auth');
        $data = input();
        $ids = is_array($data['ids'])?implode(',',$data['ids']):$data['ids'];
        if(empty($ids))$this->error('请选择产品');

        $where[] = ['id','in',$ids];
        $give_sn = Db::name('mill_order_archives_give_quality')->where($where)->column('give_sn','id');
        $give_sn = implode(",",array_values($give_sn));
        if(empty($data['give_sn']))$data['give_sn'] = $give_sn;

        if ($this->request->isPost()){

            //关闭子窗口，并刷新父窗口
            if (GiveModel::quality($user,$data,false)) $this->success('操作成功','','_parent_reload');
        }

        $info['give_sn'] = $give_sn;
        $info['status'] = '-1';
        $quality_status = GiveModel::$quality_status;
        unset($quality_status['-3']);
        unset($quality_status[0]);
        return ZBuilder::make('form')
            ->setPageTitle('质检') // 页面标题
            ->addHidden('give_sn')
            ->addStatic('give_sn', '产品编号', '', $give_sn)
            ->addFormItems([ // 批量添加表单项
                //['text:||||must', 'address_sn','发货单号', $address_sn],
                ['radio:12||||must', 'status', '质检状态','',$quality_status],
                ['radio:12||||must', 'give_status', '修复环节','',GiveModel::$give_status_search],
                ['text:12||||must', 'quality_note', '备注'],
            ])
            ->setFormData($info)
            ->submitConfirm()
            ->layout(['give_sn'=>12])
            ->fetch();

        $this->error('操作失败');
    }
    /**
     * 更新产品状态
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function able(){

        //工程ID
        $order_id = input('order_id');
        //获取发货部的产品状态
        $address_role = GiveModel::$role[8];
        $address_status = $address_role['status'][0];

        if ($this->request->isPost()){

            $role_status = input('status');
            if(!is_numeric($role_status))$this->error('请选择产品状态');

            $give_search = input('give_search');
            $give_search2 = input('give_search2');
            if(empty($give_search2))$give_search2 = $give_search;

            if(empty($give_search))$this->error('请输入起始序号');
            if($give_search<0)$this->error('输入正常的起始序号');
            if($give_search2<0)$this->error('输入正常的截止序号');
            if($give_search>$give_search2)$this->error('输入正常的序号');
            if(count(explode('-',$give_search))>1)$this->error('起始序号格式不支持');
            if(count(explode('-',$give_search2))>1)$this->error('截止序号格式不支持');

            //循环处理
            for ($i=$give_search,$j=$give_search2;$i<=$j;$i++){

                $where = [
                    ['a.sort','=',$i],
                    ['g.order_id','=',$order_id],
                    ['g.status','>=',0],
                    //['g.status','<',$role_status],
                ];

                $give = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('g.*,o.is_process')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->leftJoin('mill_order o','o.id=g.order_id')
                    ->where($where)
                    ->group('g.id')
                    ->select();

                $archives_id = '';
                foreach ($give as $gv){

                    $status = abs($gv['status']);
                    $status_flow = $gv['status_flow'];

                    //同步同产品的发货信息
                    $update = [];
                    /*$update = [
                        'address_sn'        =>  $address_give['address_sn'],
                        'address_date'      =>  $address_give['address_date'],
                        'address_time'      =>  $address_give['address_time'],
                        'address_status'    =>  $address_give['address_status'],
                        'car_id'            =>  $address_give['car_id'],
                    ];*/
                    //补上各流水线状态，默认当前操作部门用户

                    $user = session('user_auth');
                    $user['id'] = UID;
                    $user['mill_id'] = Db::name('admin_user')->where(['id'=>UID])->value('mill_id');
                    $sup_status = $role_status;//需要补充到的状态
                    $status_flow_update = GiveModel::giveToStatus4($user,$status_flow,$status,$sup_status,$gv);

                    $update = array_merge($update,$status_flow_update);
                    Db::name('mill_order_archives_give')->where(['id'=>$gv['id']])->update($update);

                    $archives_id = $gv['archives_id'];
                }
                ArchivesModel::checkStatus($archives_id,$role_status);

            }

            //关闭子窗口，并刷新父窗口
            $this->success('操作成功','','_parent_reload');
        }

        $order = Db::name('mill_order')->where(['id'=>$order_id])->find();
        return ZBuilder::make('form')
            ->setPageTitle('更新产品状态') // 页面标题
            ->addStatic('archives_sn', '档案编号', '', $order['archives_sn'])
            ->addFormItems([ // 批量添加表单项
                //['text:||||must', 'address_sn','发货单号', $address_sn],
                ['radio:12||||must', 'status', '产品状态','',GiveModel::$give_status_search],
                ['text:6||||must', 'give_search', '序号范围','开始，例：1'],
                ['text:6||||must', 'give_search2', '序号范围','截止，例：999'],
            ])
            ->submitConfirm()
            ->layout(['archives_sn'=>12])
            ->fetch();

    }

}
